package com.design.graduation.asdemo.network;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.design.graduation.asdemo.utils.JSONUtil;
import com.design.graduation.asdemo.utils.LoadingUtils;
import com.design.graduation.asdemo.utils.LogUtils;
import com.design.graduation.asdemo.utils.ToastUtil;


import java.io.IOException;

import com.design.graduation.asdemo.network.model.ApiError;
import retrofit.HttpException;
import retrofit.Response;
import rx.Observer;
import rx.exceptions.CompositeException;
import rx.exceptions.OnErrorFailedException;

/**
 * Created by liyugang on 10/26/15.
 */
public abstract class HSFObserver<T> implements Observer<T> {
    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        LoadingUtils.dismiss();
        try {
            HttpException httpException = (HttpException) e;
            Response<T> response = (Response<T>) httpException.response();
            onFailure(response.errorBody().string());
        } catch (ClassCastException classCastException) {
            throw classCastException;
        } catch (OnErrorFailedException onErrorFailedException){
            onErrorFailedException.printStackTrace();
        }catch (CompositeException compositeException){
            compositeException.printStackTrace();
        }

        catch (JSONException jsonException) {
            jsonException.printStackTrace();
            ToastUtil.showShortToast("服务器开小差了，稍后再试...");
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } catch (Exception exception) {
            exception.printStackTrace();
            throw exception;
        }


    }

    @Override
    public void onNext(T t) {
        LogUtils.i(JSONUtil.toJSONString(t));
        onSuccess(t);
    }

    public abstract void onSuccess(T t);

    public void onFailure(String json) {
        LogUtils.e(json);
        ApiError errorResult = JSON.parseObject(json, ApiError.class);
        ToastUtil.showShortToast(errorResult.getMessage());
    }
}
